import 'dart:convert';

/// 资讯内容模型
class Content {
  final int contentId;
  final int articleId;
  final String language;
  final String? summary;
  final List<Sentence>? sentences;
  final String? createTime;
  final String? updateTime;

  Content({
    required this.contentId,
    required this.articleId,
    required this.language,
    this.summary,
    this.sentences,
    this.createTime,
    this.updateTime,
  });

  factory Content.fromJson(Map<String, dynamic> json) {
    List<Sentence>? sentenceList;
    if (json['sentences'] != null) {
      if (json['sentences'] is String) {
        // 如果是字符串，需要先解析 JSON
        try {
          final dynamic parsed = jsonDecode(json['sentences']);
          if (parsed is List) {
            sentenceList = parsed
                .map((item) => Sentence.fromJson(item as Map<String, dynamic>))
                .toList();
          }
        } catch (e) {
          print('解析 sentences 失败: $e');
          sentenceList = null;
        }
      } else if (json['sentences'] is List) {
        sentenceList = (json['sentences'] as List)
            .map((item) => Sentence.fromJson(item as Map<String, dynamic>))
            .toList();
      }
    }

    return Content(
      contentId: json['contentId'],
      articleId: json['articleId'],
      language: json['language'] ?? 'cn',
      summary: json['summary'],
      sentences: sentenceList,
      createTime: json['createTime'],
      updateTime: json['updateTime'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'contentId': contentId,
      'articleId': articleId,
      'language': language,
      'summary': summary,
      'sentences': sentences?.map((item) => item.toJson()).toList(),
      'createTime': createTime,
      'updateTime': updateTime,
    };
  }
}

/// 句子模型
class Sentence {
  final int index;
  final String text;

  Sentence({
    required this.index,
    required this.text,
  });

  factory Sentence.fromJson(Map<String, dynamic> json) {
    return Sentence(
      index: json['index'],
      text: json['text'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'index': index,
      'text': text,
    };
  }
}

